//
//  MainApi.m
//  LuxuryGoods
//
//  Created by 刘星辰 on 2018/5/19.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "MainApi.h"
#import <AFNetworking/AFNetworking.h>
#import "UIImage+Base64.h"
#import "UserInfoModel.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "NSDictionary+NetWork.h"

#define    BaseApi       @"http://api.shewuwang.com/api/"

@interface MainApi ()

@property (nonatomic, strong) AFHTTPSessionManager *manager;

@end

static MainApi *request = nil;

@implementation MainApi
+ (MainApi *)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        request = [[MainApi alloc] init];
    });
    return request;
}

- (instancetype)init {
    if (self == [super init]) {
        self.manager = [AFHTTPSessionManager manager];
        self.manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript",@"text/plain", nil];
        [self.manager.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        
    }
    return self;
}

- (void)getPath:(NSString *)path params:(NSDictionary *)params resultBlock:(ResultBlock)resultBlock {
    return [self dataTaskWithHTTPMethod:@"GET" URLString:path parameters:params  resultBlock:resultBlock];
}

- (void)postPath:(NSString *)path params:(NSDictionary *)params resultBlock:(ResultBlock)resultBlock {
    return [self dataTaskWithHTTPMethod:@"POST" URLString:path parameters:params  resultBlock:resultBlock];
}

- (void)dataTaskWithHTTPMethod:(NSString *)method
                     URLString:(NSString *)URLString
                    parameters:(id)parameters
                   resultBlock:(ResultBlock)resultBlock {
    

//    NSMutableDictionary *data = [NSMutableDictionary dictionary];
//    if (parameters) {
//        [data addEntriesFromDictionary:parameters];
//
//    }
//    [data addEntriesFromDictionary:@{@"apiCode" : URLString}];
//    [self transferValueImageToBase64With:data];
    [SVProgressHUD show];
//    NSDictionary *params = @{@"json" : [data parametersString:data]};
    
    NSString *urlString = [BaseApi stringByAppendingString:URLString];
    
    if ([method isEqualToString:@"POST"]) {
        
        [self.manager POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"method == %@ pram == %@  Response Object:\n%@",urlString,parameters,responseObject);
            if ([responseObject[@"code"] integerValue] == 1)
            {
                [SVProgressHUD dismiss];
                if (resultBlock)
                {
                     resultBlock(responseObject,nil);
                }
               
            }
            else
            {
                 [SVProgressHUD dismiss];
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                if (resultBlock)
                {
                    resultBlock(nil,[NSError errorWithDomain:responseObject[@"msg"] code:400 userInfo:nil]);
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (error) {
                [SVProgressHUD dismiss];
                NSLog(@"Error --->>> \n%@", error);
                if (resultBlock)
                {
                    resultBlock(nil,error);
                }
            }
        }];
    }else if([method isEqualToString:@"GET"]){
        
        [self.manager GET:urlString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"method == %@ pram == %@  Response Object:\n%@",urlString,parameters,responseObject);
            if ([responseObject[@"code"] integerValue] == 1)
            {
                [SVProgressHUD dismiss];
                if (resultBlock)
                {
                    resultBlock(responseObject,nil);
                }
                
            }
            else
            {
                 [SVProgressHUD dismiss];
                [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
                if (resultBlock)
                {
                    resultBlock(nil,[NSError errorWithDomain:responseObject[@"msg"] code:400 userInfo:nil]);
                }
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (error) {
                [SVProgressHUD dismiss];
                NSLog(@"Error --->>> \n%@", error);
                if (resultBlock)
                {
                    resultBlock(nil,error);
                }
            }
        }];
    }
    
}

- (void)sendPostUploadFilePath:(NSString *)path params:(NSDictionary *)params fileDic:(NSDictionary *)fileDic resultBlock:(ResultBlock)resultBlock{
    
    NSString *urlString = [BaseApi stringByAppendingString:path];
    [self.manager POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSString *key in  fileDic)
        {
            
            // 上传文件路径
            //            NSString *filePath = [self.fileDic objectForKey:key];
            //            NSString *fileName = [filePath substringFromIndex:[filePath rangeOfString:@"/" options:NSBackwardsSearch].location + 1];
            ////            //把要上传的图片转成NSData
            //            NSData*fileData = [NSData dataWithContentsOfFile:filePath];
            NSData * fileData;
            NSString * fileName = key;
            NSString * mimeType ;
            if ([[ fileDic objectForKey:key] isKindOfClass:[UIImage class]]) {
                
                UIImage * image = [ fileDic objectForKey:key];
                fileData =UIImageJPEGRepresentation(image,0.5);
                mimeType = @"image/png";
                
                /*常用数据流类型：
                 
                 @"image/png" 图片
                 
                 @“video/quicktime” 视频流
                 
                 */
                [formData appendPartWithFileData:fileData name:fileName fileName:[NSString stringWithFormat:@"%@.jpg",fileName] mimeType:mimeType];//给定数据流的数据名，文件名，文件类型（以图片为例）
            }else{
                [ fileDic objectForKey:key];
                [formData appendPartWithFileURL:[fileDic objectForKey:key] name:@"file" error:nil];
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"进度表示形式1：%f", uploadProgress.fractionCompleted);
        NSLog(@"进度表示形式2：%@", uploadProgress.localizedDescription);
        NSLog(@"进度表示形式3：%@", uploadProgress.localizedAdditionalDescription);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"==%@",responseObject); //返回结果
        if ([responseObject[@"code"] integerValue] == 1)
        {
            [SVProgressHUD dismiss];
            if (resultBlock)
            {
                resultBlock(responseObject,nil);
            }
            
        }
        else
        {
            [SVProgressHUD dismiss];
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            if (resultBlock)
            {
                resultBlock(nil,[NSError errorWithDomain:responseObject[@"msg"] code:400 userInfo:nil]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传失败%@",error.localizedDescription);//请求失败结果
        if (error) {
            [SVProgressHUD dismiss];
            NSLog(@"Error --->>> \n%@", error);
            if (resultBlock)
            {
                resultBlock(nil,error);
            }
        }
    }];
}


- (void)sendPostMutiUploadFilePath:(NSString *)path params:(NSDictionary *)params fileDic:(NSDictionary *)fileDic resultBlock:(ResultBlock)resultBlock{
    
    NSString *urlString = [BaseApi stringByAppendingString:path];
    [self.manager POST:urlString parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for (NSString *key in  fileDic)
        {
            
            // 上传文件路径
            //            NSString *filePath = [self.fileDic objectForKey:key];
            //            NSString *fileName = [filePath substringFromIndex:[filePath rangeOfString:@"/" options:NSBackwardsSearch].location + 1];
            ////            //把要上传的图片转成NSData
            //            NSData*fileData = [NSData dataWithContentsOfFile:filePath];
            NSData * fileData;
            NSString * fileName = @"files[]";
            NSString * mimeType ;
            if ([[ fileDic objectForKey:key] isKindOfClass:[UIImage class]]) {
                
                UIImage * image = [ fileDic objectForKey:key];
                fileData =UIImageJPEGRepresentation(image,0.5);
                mimeType = @"image/png";
                
                /*常用数据流类型：
                 
                 @"image/png" 图片
                 
                 @“video/quicktime” 视频流
                 
                 */
                [formData appendPartWithFileData:fileData name:fileName fileName:[NSString stringWithFormat:@"%@.jpg",fileName] mimeType:mimeType];//给定数据流的数据名，文件名，文件类型（以图片为例）
            }else{
                [ fileDic objectForKey:key];
                [formData appendPartWithFileURL:[fileDic objectForKey:key] name:@"file" error:nil];
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"进度表示形式1：%f", uploadProgress.fractionCompleted);
        NSLog(@"进度表示形式2：%@", uploadProgress.localizedDescription);
        NSLog(@"进度表示形式3：%@", uploadProgress.localizedAdditionalDescription);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"==%@",responseObject); //返回结果
        if ([responseObject[@"code"] integerValue] == 1)
        {
            [SVProgressHUD dismiss];
            if (resultBlock)
            {
                resultBlock(responseObject,nil);
            }
            
        }
        else
        {
            [SVProgressHUD dismiss];
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
            if (resultBlock)
            {
                resultBlock(nil,[NSError errorWithDomain:responseObject[@"msg"] code:400 userInfo:nil]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"上传失败%@",error.localizedDescription);//请求失败结果
        if (error) {
            [SVProgressHUD dismiss];
            NSLog(@"Error --->>> \n%@", error);
            if (resultBlock)
            {
                resultBlock(nil,error);
            }
        }
    }];
}

- (NSDictionary *)addUserToken:(NSDictionary *)params
{
    NSMutableDictionary *mutParams;
    if (params != nil)
    {
        mutParams = [NSMutableDictionary dictionaryWithDictionary:params];
    }
    else
    {
        mutParams = [NSMutableDictionary dictionary];
    }
    [mutParams addEntriesFromDictionary:@{@"userToken":UserInfo.userToken}];
    return mutParams;
}

//将字典中图片对象转换成base64字符串
- (NSMutableDictionary *)transferValueImageToBase64With:(NSMutableDictionary *)dict
{
    for (NSString * key in dict.allKeys)
    {
        id value = dict[key];
        if ([value isKindOfClass: [UIImage class]])
        {
            UIImage *image = (UIImage *)value;
            [dict setObject:image.base64EncodedString forKey:key];
        }
    }
    return dict;
}

@end
